package com.dao;

import com.model.Users;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class UsersDao{
	private SessionFactory sessionFactory;
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
    public ArrayList<Users> getList_hibernate(){
        Session session = null;
        Transaction tx = null;
        session =  sessionFactory.openSession();
        tx = session.beginTransaction();
        Query query =session.createQuery("from Users");
        List<Users> list = query.list();
        for (Users userEntity : list) {
            System.out.println(userEntity);
        }
        tx.commit();
       
        return (ArrayList<Users>) list;
    }
	

	
	public   Users found_hibernate(String name ,String password){
		Users u = null;
		SessionFactory sf = sessionFactory;
		Session session = sf.openSession();
		try{
		String hql = "from Users as u where u.userName = ? and u.password = ?";
		Query query = session.createQuery(hql);
		query.setString(0, name);
		query.setString(1, password);
		u = (Users)query.uniqueResult();
		System.out.println(u);
		}catch(Exception e) {
			return null;
		}finally{
			session.close();
			sf = null;
			System.out.println("close");
		}
		return u;
	}
	
	public  void insert_hibernate(Users users) {
		Session session = sessionFactory.openSession();
		Transaction trans = session.beginTransaction();
		session.save(users);
		trans.commit();
		session.close();
	}
}
